<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 添加用户输入框 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList" @change="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList">
            </el-button>
          </el-input>
        </el-col>
        <el-col :span="17">
          <el-button type="primary" @click="addDialogVisible=true">添加用户
          </el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="userList" border stripe style="width: 100%">
        <el-table-column type="index" label="#">
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="100px">
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
        </el-table-column>
        <el-table-column prop="mobile" label="电话">
        </el-table-column>
        <el-table-column prop="role_name" label="角色">
        </el-table-column>
        <!-- switch -->
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStatusChanged(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <!-- 3btn -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="remove(scope.row.id)">
            </el-button>
            <el-tooltip content="角色分配" placement="top" :enterable=false>
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="roluBtn(scope.row)">
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="resetaddForm">
        <!-- 主体区域 -->
        <el-form ref="addForm" :model="addForm" label-width="80px" :rules="addFormRules">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveAddForm">确 定
          </el-button>
        </span>
      </el-dialog>
      <!-- 编辑用户对话框 -->
      <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%" @close="reseteditForm">
        <!-- 主体区域 -->
        <el-form ref="editForm" :model="editForm" label-width="80px" :rules="addFormRules">
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEditForm">确 定
          </el-button>
        </span>
      </el-dialog>
      <!-- 角色分配对话框 -->
      <el-dialog title="分配角色" :visible.sync="ruleDialogVisible" width="50%" @close='rulesColse'>
        <!-- 主体区域 -->
        <div>
          <p>当前的用户: {{rowInfo.username}}</p>
          <p style="margin:20px 0">当前的角色: {{rowInfo.role_name}}</p>
          <p>分配新角色:
            <el-select v-model="selectRuleId" placeholder="请选择">
              <el-option v-for="item in rowList" :key="item.id" :label="item.roleName" :value="item.id">
              </el-option>
            </el-select>
          </p>
        </div>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="ruleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRule">确 定
          </el-button>
        </span>
      </el-dialog>
    </el-card>

  </div>
</template>
<script>
export default {
  data () {
    var EmailRule = (rule, value, callback) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (!regEmail.test(value)) {
        return callback(new Error('邮箱格式不正确'))
      }
      callback()
    }
    var mobileRule = (rule, value, callback) => {
      const regMobile = /^1[34578]\d{9}$/
      if (!regMobile.test(value)) {
        return callback(new Error('手机号不正确'))
      }
      callback()
    }
    return {
      queryInfo: {
        query: '', // 查询参数
        pagenum: 1, // 当前页数
        pagesize: 5 // 页数据条数
      },
      // 用户数据
      userList: [],
      // 数据总条数
      total: 0,
      // 添加用户对话框 默认隐藏
      addDialogVisible: false,
      // 添加用户表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单校验规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: EmailRule, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: mobileRule, trigger: 'blur' }
        ]
      },
      // 编辑用户对话框 默认隐藏
      editDialogVisible: false,
      // 编辑用户表单
      editForm: {},
      // 角色分配会话框显示隐藏
      ruleDialogVisible: false,
      // 当前用户信息
      rowInfo: {},
      // 角色列表
      rowList: [],
      // 选中的角色
      selectRuleId: null
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    // 渲染用户列表数据
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      // console.log(res)
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 分页条数改变
    handleSizeChange (size) {
      this.queryInfo.pagesize = size
      this.getUserList()
    },
    // 页码值改变
    handleCurrentChange (current) {
      this.queryInfo.pagenum = current
      this.getUserList()
    },
    // switch开关
    async userStatusChanged (row) {
      const { data: res } = await this.$http.put(`users/${row.id}/state/${row.mg_state}`)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('设置状态失败')
      this.$message.success('设置状态成功')
    },
    // 用户请求点击提交
    saveAddForm () {
      this.$refs.addForm.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)
        // console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    // 添加用户对话框关闭
    resetaddForm () {
      this.$refs.addForm.resetFields()
    },
    // 编辑用户对话框弹出
    showEditDialog (row) {
      this.editDialogVisible = true
      // console.log(row)
      // const { data: res } = await this.$http.get(`users/${row.id}`)
      // if (res.meta.status !== 200) return this.$message.error('获取用户信息失败')
      // this.editForm = res.data
      this.editForm = { ...row }
    },
    // 编辑用户对话框关闭
    reseteditForm () {
      this.$refs.editForm.resetFields()
    },
    // 编辑用户点击提交
    saveEditForm () {
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(`users/${this.editForm.id}`,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          })
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改成功')
        this.editDialogVisible = false
        this.getUserList()
      })
    },
    // 删除用户数据
    remove (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`users/${id}`)
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.getUserList()
        this.$message.success('删除成功!')
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 权限分配
    async roluBtn (row) {
      console.log(row)
      this.rowInfo = row
      this.ruleDialogVisible = true
      const { data: res } = await this.$http.get('roles')
      console.log(res)
      this.rowList = res.data
    },
    // 分配权限点击提交
    async saveRule () {
      if (!this.selectRuleId) return this.$message.info('请选择角色')
      const { data: res } = await this.$http.put(`users/${this.rowInfo.id}/role`, { rid: this.selectRuleId })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('分配角色失败')
      this.$message.success(res.meta.msg)
      this.ruleDialogVisible = false
    },
    // 关闭分配权限会话框
    rulesColse () {
      this.selectRuleId = null
      this.rowInfo = {}
    }

  }
}
</script>

<style scoped lang='less'>
</style>
